package com.google.code.synchronized_player;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;

import android.util.Log;

public class Controller implements Runnable {
	ConcurrentLinkedQueue<Command> executeQueue = new ConcurrentLinkedQueue<Command>();
	NetReceiver netReceiver;
	NetSender netSender;
	Thread thread;

	public void EnqueueCommand(Command c) {
		synchronized (executeQueue) {
			executeQueue.add(c);
			executeQueue.notify();
		}
	}
	
	PlayList playlist;
	public Controller(int listenPort, String IP, int port, PlayList mplaylist)
			throws UnknownHostException, IOException {
		playlist = mplaylist;
		netReceiver = new NetReceiver(listenPort, this);
		netSender = new NetSender(port, IP);

		thread = new Thread(this);
		thread.setDaemon(true);
		thread.start();
	}

	public void SendPlaylist(String currentTrack, String Position,
			String[] strings) {
		Log.d("", "send playlist");
		netSender.Enqueue(Command.Parse("plbegin " + currentTrack + " " + Position));
 
		for (String item : strings) {
			netSender.Enqueue(Command.Parse("plitem " + item));
		}
		netSender.Enqueue(Command.Parse("plend"));
	}

	public void run() {
		while (true) {
			Command c = null;
			synchronized (executeQueue) {
				while ((c = executeQueue.poll()) == null) {
					try {
						executeQueue.wait();
					} catch (InterruptedException e) {
						return;
					}
				}
			}
			
			Execute(c);
		}
	}

	public void Execute(Command c) {
		String name = c.getName();
		Log.d("SynchronizedPlayer", "Executing command " + name);
		if (name.equals("plbegin")) {
			String currentTrack = c.getArg(0);
			String currentPosition = c.getArg(1);
			ArrayList<String> plitems = new ArrayList<String>();
			boolean inPlayList = true;
			while (inPlayList) {
				while ((c = executeQueue.poll()) != null) {
					if (c.getName().equals("plitem")) {
						Log.d("SynchronizedPlayer",
								"got command " + c.getName());
						plitems.add(c.getArg(0));
					} else if (c.getName().equals("plend")) {
						inPlayList = false;
						break;
					}
				}
			}
			String[] items = new String[plitems.size()];
			for (int i = 0; i < plitems.size(); i++) {
				items[i] = (String)(plitems.get(i));
			}
			playlist.importFromString(currentTrack, currentPosition, items);
		}
	}
}
